package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.ProductBean;
import com.project.bean.SellBean;
import com.project.bean.SellCarBean;
import com.project.mapper.IProductMapper;
import com.project.mapper.ISellCarMapper;
import com.project.mapper.ISellInfoMapper;
import com.project.mapper.ISellMapper;
import com.project.service.ISellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class SellServiceImpl implements ISellService {
    @Autowired
    private ISellMapper sellMapper;
    @Autowired
    private ISellCarMapper sellCarMapper;
    @Autowired
    private ISellInfoMapper sellInfoMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public void add(Integer userId, SellBean sellBean) {
        sellBean.setTotalPrice(sellCarMapper.getTotalPrice(userId));
        sellMapper.insert(sellBean);
        List<SellCarBean> list = sellCarMapper.findByUserId(userId);
        sellInfoMapper.addInfo(list, sellBean.getId());
        for (SellCarBean carBean : list
        ) {
            ProductBean product = productMapper.selectById(carBean.getProductId());
            product.setNum(product.getNum() - carBean.getNum());
            productMapper.updateById(product);
        }
        QueryWrapper<SellCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        sellCarMapper.delete(qw);
    }

    @Override
    public IPage<SellBean> findByItem(Integer pageNO, String name, LocalDate startDate, LocalDate endDate) {
        return sellMapper.findByItem(new Page(pageNO, 3), name, startDate, endDate);
    }

    @Override
    public SellBean findById(Integer id) {
        SellBean sellBean = sellMapper.findById(id);
        sellBean.setInfoList(sellInfoMapper.findList(id));
        return sellBean;
    }
}
